package com.dkd.handler;

import cn.elegent.ac.ACHandler;
import cn.elegent.ac.ElegentAC;
import cn.elegent.ac.annotation.Topic;
import com.dkd.config.TopicConfig;
import com.dkd.config.constant.TaskType;
import com.dkd.contract.AutoSupplyContract;
import com.dkd.contract.SupplyContract;
import com.dkd.exception.LogicException;
import com.dkd.feign.TaskService;
import com.dkd.service.VendingMachineService;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author DiXiaoNie
 * @since 2023/2/2 17:33
 */

@Topic(TopicConfig.VMS_AUTO_SUPPLY_TOPIC)
public class AutoSupplyHandler implements ACHandler<AutoSupplyContract> {
    @Autowired
    private ElegentAC elegentAC;

    @Autowired
    private VendingMachineService vendingMachineService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String topic, AutoSupplyContract autoSupplyContract) throws Exception {
        //获取商品库存率
        int ratio = this.vendingMachineService.countCapacityRatio(autoSupplyContract.getInnerCode(), autoSupplyContract.getSkuId());
        //获取补货工单警戒线
        Integer supplyAlertValue = this.taskService.getSupplyAlertValue();
        //如果低于警戒线
        if (ratio <= supplyAlertValue.intValue()) {
            //判断是否存在未完成的补货工单
            Boolean hasTask = this.taskService.hasTask(autoSupplyContract.getInnerCode(), TaskType.TASK_TYPE_SUPPLY);
            if (hasTask == null || hasTask.booleanValue() == false) {
                SupplyContract supplyContract = this.vendingMachineService.buildSupplyContract(autoSupplyContract.getInnerCode());
                this.elegentAC.publish(TopicConfig.TASK_SUPPLY_TOPIC, supplyContract);
            } else {
                throw new LogicException("存在未完成的补货订单");
            }
        }
    }
}
